<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group v-model="searchParams.resourceType" @change="onTabChange">
						<el-radio-button v-for="item in tabList" :key="item.code" :label="item.code">{{ item.name }}</el-radio-button>
					</el-radio-group>
					<!--<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
					<!--<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						class="item-gap"
						size="small"
						@click="onReportBtn"
					>导出</jk-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						size="small"
						class="item-gap"
						@click="onReportBtn2"
					>导出</jk-button>
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<div class="search-bar-item-size2 item-gap">
						<el-date-picker v-model="searchParams.belongDate" :clearable="false" size="small" style="width: 100%;" type="date" value-format="yyyy-MM-dd" placeholder="日期" />
					</div>
					<el-select v-model="searchParams.groupId" placeholder="班次" size="small" class="search-bar-item-size3 margin-5-0 item-gap">
						<el-option v-for="item in scheduleShiftList" :key="item.id" :label="`${item.name}${item.time}`" :value="item.id" />
					</el-select>
					<el-select v-model="searchParams.deviceRecordNumber" clearable placeholder="机台" size="small" class="search-bar-item-size1 margin-5-0 item-gap">
						<el-option v-for="item in machineList" :key="item" :label="item" :value="item" />
					</el-select>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table v-if="!showTable" ref="jkTable" border :span-method="mergeColMethod" :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<el-tag v-if="item.keyName === 'deviceRecordNumber'" type="primary">{{ scope.row.deviceRecordNumber }}</el-tag>
						<span v-else-if="item.keyName === 'groupId'">{{ scheduleShiftList.find(x => x.id === scope.row.groupId).name }}</span>
						<!--<div v-else-if="item.keyName === 'spunYarnColors'">
							<div class="link-style text-right">{{ scope.row[item.keyName] ? scope.row[item.keyName].map(x => x.name).join() : '' }}</div>
						</div>
						<div v-else-if="item.keyName === 'paperTubeList'">
							<div class="link-style text-right">{{ scope.row[item.keyName] ? scope.row[item.keyName].map(x => x.name).join() : '' }}</div>
						</div>-->
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatDate, tipsBar, firstCharacterToLowerCase } from '/src/utils/jk/jk-tool';
    import {
        productionPrdReportDelete,
        productionPrdReportUpdateStatus, iotCollectDataLtCutPage
    } from '/src/api/production/xsReport';
    import { getInfo } from '../../../api/login';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { exportExcelMerge } from '../../../api/commont';
    import { systemUserColumnConfigGet } from '../../../api/system/column-config';

    export default {
        name: 'CutReport',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                showTable: false,
                activeTab: '',
                tabList: [],
                apiItem: {
                    'page': iotCollectDataLtCutPage,
                    'exportExcel': iotCollectDataLtCutPage,
                    'delete': productionPrdReportDelete
                },
                prefix: 'production:prdOrder',
                scheduleShiftList: [
                    { id: 1, name: '早班', time: '（07:30 ~ 19:30）' },
                    { id: 2, name: '晚班', time: '（19:30 ~ 07:30）' }
                ],
                versionRecordDialogState: false,
                noticeStateList: [
                    { id: 0, name: '待核查' },
                    { id: 1, name: '已核查' }
                ],
                machineList: [
                    'LT001',
                    'LT002',
                    'LT003',
                    'LT004',
                    'LT005',
                    'LT006',
                    'LT007',
                    'LT008',
                    'LT009'
                ],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: 1000,
                    code: '',
                    resourceType: null,
                    groupId: 1,
                    deviceRecordNumber: '',
                    belongDate: '',
                    shiftName: '',
                    processName: '',
                    auditState: null,
                    workshopId: null,
                    processCode: 'LT'
                },
                dropdownOption: [
                    { code: 'RELEASE', name: '核查通过', isShow: true, icon: 'el-icon-s-check', allowState: 0, api: productionPrdReportUpdateStatus },
                    { code: 'CANCEL_RELEASE', name: '撤回', isShow: true, icon: 'el-icon-circle-close', allowState: 1, api: productionPrdReportUpdateStatus },
                    { code: 'DETAIL', name: '详情', isShow: true, icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'DELETE', name: '删除', isShow: true, icon: 'el-icon-delete', allowState: 0, api: productionPrdReportDelete }
                ]
            };
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.getDependentData();
        },
        methods: {
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageSize', size);
                this.$set(this.searchParams, 'pageNo', e);
                this.getListRequest();
            },
            onTabChange(e) {
                this.tableColumnList = this.tabList.find(x => x.code === e).itemList;
                this.showTable = true;
                this.getListRequest();
                this.$nextTick(() => {
                    this.showTable = false;
                });
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: firstCharacterToLowerCase(this.$route.name), filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res.columnConfigList ? JSON.parse(JSON.stringify(res.data.res.columnConfigList)) : [];
                        this.tabList = resData ? resData.map(x => {
                            x.code = Number(x.code);
                            return x;
                        }) : [];
                        this.tableColumnList = resData && resData.length ? resData[0].itemList : [];
                        this.$set(this.searchParams, 'resourceType', resData && resData.length ? resData[0].code : null);
                    }
                });
            },
            onReportBtn2() {
                const titleList = this.tableColumnList.map(x => x.title);
                const valueList = [];
                let rowArr = [];
                const cpData = this.tableData ? JSON.parse(JSON.stringify(this.tableData)) : [];
                cpData.forEach(x => {
                    x.groupId = this.scheduleShiftList.find(k => k.id === x.groupId).name;
                });
                cpData.forEach(d => {
                    rowArr = [];
                    this.tableColumnList.forEach(h => {
                        rowArr.push(d[h.keyName]);
                    });
                    valueList.push(rowArr);
                });
                const fileName = `${this.$route.meta.title}(${formatDate(this.searchParams.belongDate, '')})`;
                if (cpData.length) {
                    exportExcelMerge({
                        titleList,
                        valueList,
                        mergedKey: '机台',
                        fileName: fileName
                    }).then(res => {
                        if (res.data.status === 200) {
                            const href = 'http://spin.jeacon.cn/excel' + res.data.res.path;
                            const downA = document.createElement('a');
                            downA.href = href;
                            downA.click();
                            // 销毁超连接
                            window.URL.revokeObjectURL(href);
                            // this.$download.excel(res.data, '络筒产量统计');
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '当前没有数据可以导出!');
                }
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['deviceRecordNumber']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onVisibleChange(e) {
                this.versionRecordDialogState = e;
            },
            onDropdownChange(type, { id }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem) {
                    if (optionItem.code === 'DETAIL') {
                        this.onDetailBtn({ id });
                    } else {
                        this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                            optionItem.api({ id: id }).then(res => {
                                if (res.data.status === 200) {
                                    this.getListRequest();
                                }
                            });
                        }).catch(() => {});
                    }
                }
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailXsReport',
                    query: {
                        id: row.id
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = this.transformResData(res);
                        this.totalCount = res.data.count;
                    }
                });
            },
            transformResData(res) {
                const arr = [];
                if (res.data.res.length) {
                    let header = [];
                    if (res.data.res) {
                        res.data.res.forEach(x => {
                            if (x.group && x.group.length && !header.length) {
                                header = x.group[0];
                            }
                        });
                    }
                    let item = {};
                    res.data.res.map(x => {
                        if (x.group.length) {
                            x.group.forEach((p, pIdx) => {
                                item = {};
                                item.deviceRecordId = x.deviceRecordId;
                                item.deviceRecordNumber = x.deviceRecordNumber;
                                item.belongDate = this.searchParams.belongDate;
                                item.groupId = this.searchParams.groupId;
                                item.sortNum = pIdx + 1;
                                for (const k in header) {
                                    item[k] = p[k];
                                }
                                arr.push(item);
                            });
                        } else {
                            item = {};
                            item.deviceRecordId = x.deviceRecordId;
                            item.deviceRecordNumber = x.deviceRecordNumber;
                            item.belongDate = this.searchParams.belongDate;
                            item.groupId = this.searchParams.groupId;
                            arr.push(item);
                        }
                        return x;
                    });
                }
                return arr;
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.$toOtherRouter({ name: 'addXsReport' });
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'editXsReport',
                    query: {
                        id: row.id
                    }
                });
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem['delete']({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['exportExcel'](params);
                }).then(res => {
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = this.tableColumnList.map(x => x.title);
                            const filterVal = this.tableColumnList.map(x => x.keyName);
                            const list = this.transformResData(res).map(item => {
                                item.groupId = this.scheduleShiftList.find(x => x.id === item.groupId).name;
                                return item;
                            });
                            const data = this.formatJson(filterVal, list);
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `${this.$route.meta.title}(${formatDate(this.searchParams.belongDate, '')}${list.length ? list[0].groupId : ''})`,
                                autoWidth: true,
                                bookType: 'xls'
                            });
                        });

                        // this.$download.excel(arr, `${this.$route.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            }
        }
    };
</script>
<style>
    .machine-group-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-left: solid 1px #eee;
        border-top: solid 1px #eee;
        width: 80px;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 0 4px;
        flex-shrink: 0;
    }
</style>
